<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "xhtml1-transitional.dtd">
<html>
<head>
<title>jqMock User Guide</title>
<link type="text/css" rel="stylesheet"  href="jqMock.css" />
<link type="text/css" rel="stylesheet" href="highlighter/SyntaxHighlighter.css" />
</head>
<body>

<h1>jqMock User Guide</h1>

<ul id="nav">
	<li><a href="http://code.google.com/p/jqmock/">Home</a></li>
	<li><a href="download.html">Download</a></li>
	<li><a class="current">UserGuide</a></li>
	<li><a href="api.html">API</a></li>
	<li><a href="faq.html">FAQ</a></li>
	<li><a href="../src/jqMock.html">Tests</a></li>
	<li class="last"><a href="http://users.tpg.com.au/fuzziman/jqmock/jscoverage/jscoverage.html?jqMock.html">Coverage</a></li>
</ul><br style="clear:both;"/>

<h2>Overview</h2>
<p>jqMock is a lightweight javascript Mock Framework for the jqUnit testing framework. jqMock allows functions in dependent functions such as native alert dialogs to be mocked, so that your own code can be tested in isolation.</p>
<p>jqMock has comprehensive expectation support, with complex argument matching criteria, ordered/unordered expectations, multiplicity control, intercepting return values and throwing exceptions. Error messages are clear and explicit, and failures are presented with full details of the satisfaction state.</p>

<h2>Getting Started</h2>
<p>It is assumed you are already familiar with the <a href="http://code.google.com/p/jqunit/"> jqUnit testing framework</a>.</p>
<p>Download the source for jqMock here:</p>
<ul>
<li><a href="http://jqmock.googlecode.com/svn/trunk/src/jqMock.js">download</a></li>
</ul>
<p>To include in your tests, add the script to your fixture:</p>
<pre name="code" class="html:nocontrols:nogutter">
&lt;script type="text/javascript" src="jqMock.js"&gt;&lt;/script&gt;
</pre>

<p>It is also suggested you make a call to <strong>jqMock.addShortcut()</strong> which puts <strong>is</strong> and <strong>expect</strong> into the global scope for cleaner code:</p>
<pre name="code" class="js:nocontrols:nogutter">
jqMock.addShortcut();
</pre>



<h2>The Basics</h2>


<h3>assert that</h3>
<p>jqMock provides an assertion function <strong>assertThat</strong> which allows you to setup powerful and flexible expectations by providing a comprehensive set of expressions. Even if you do not use this framework for mocking, <strong>assertThat</strong> is a very useful addition to the jqUnit toolset. For example:</p>
<pre name="code" class="js:nocontrols:nogutter">
jqMock.assertThat(3,3);
jqMock.assertThat([1,2,3],[1,2,3]);	
jqMock.assertThat({a:'a',b:'b'}, {b:'b', a:'a'});
jqMock.assertThat([1,2,3], is.instanceOf(Array));
jqMock.assertThat("foo", is.anyOf(['foo','bar']));
jqMock.assertThat(myobject, is.allOf([is.instanceOf(MyObject),{x:'x'}]));
</pre>



<h3>Expressions</h3>
<p>jqMock comes with the following expressions:</p>
<table>
<tr><th>Expression</th><th>Meaning</th><th style="width:50%">Example</th></tr>
<tr>
    <td>is.anything</td><td>matches anything</td>
    <td>
        <pre name="code" class="js:nocontrols:nogutter">
            jqMock.assertThat(foo, is.anything);        
        </pre>
    </td>
</tr>
    <tr><td>is.not()</td><td>negate an expression</td>
    <td>
        <pre name="code" class="js:nocontrols:nogutter">
            jqMock.assertThat(foo, is.not(100));        
        </pre>
    </td>
</tr>
<tr>
    <td>is.instanceOf()</td><td>applies the instanceof operator</td>
    <td>
        <pre name="code" class="js:nocontrols:nogutter">
            jqMock.assertThat([1,2,3], is.instanceOf(Array));        
        </pre>
    </td>
</tr>
<tr>
    <td>is.regex()</td><td>whether it matches the regex expression provided</td>
    <td>
        <pre name="code" class="js:nocontrols:nogutter">
            jqMock.assertThat("987", is.regex(/[0-9]*/));       
        </pre>
    </td>    
</tr>
<tr>
    <td>is.anyOf([])</td><td>matches one of the expressions in the array provided</td>
    <td>
        <pre name="code" class="js:nocontrols:nogutter">
            jqMock.assertThat(foo, is.anyOf(["a", "b", "c"]));       
        </pre>
    </td>    
</tr>
<tr>
    <td>is.allOf([])</td>
    <td>must match all of the expressions in the array provided. Useful for matching multiple not expressions</td>
    <td>
        <pre name="code" class="js:nocontrols:nogutter">
            jqMock.assertThat(foo, is.allOf([is.not(null), is.not(undefined)]));       
        </pre>
    </td>    
</tr>
<tr>
    <td>is.objectThatIncludes()</td><td>matches if the actual object has every field specified in the expected object</td>
    <td>
        <pre name="code" class="js:nocontrols:nogutter">
            jqMock.assertThat({x:'x', a:'a', y:'y'}, is.objectThatIncludes({a:'a'}));
        </pre>
    </td>        
</tr>
<tr>
    <td>is.custom(Function)</td>
    <td>specify a custom expression as a function that takes in a single argument and returns a boolean value</td>
    <td>
        <pre name="code" class="js:nocontrols:nogutter">
        function isEven(arg) {
	        return arg % 2 == 0 ;
        };
        jqMock.assertThat(foo, is.custom(isEven));
        </pre>
    </td>
</tr>
<tr>
    <td>is.exception()</td>
    <td>An expression for matching exceptions, to be used with expectThatExceptionThrown(). See the section below for the different ways to create this expression.</td>
    <td>
        <pre name="code" class="js:nocontrols:nogutter">
		jqMock.expectThatExceptionThrown(function() {
			throw new Error("something bad happened");
		}, is.exception("something bad happened"));	
        </pre>
    </td>
</tr>
</table>



<h3>Asserting Exceptions</h3>
<p>jqMock also provides a method <b>expectThatExceptionThrown</b> to assert that an exception is thrown in a block of code. The following examples shows how loose or strict this assertion can be.</p>
<pre name="code" class="js:nocontrols:nogutter">
	// simple compare
	jqMock.expectThatExceptionThrown(function() {
		throw "blah";
	}, "blah");
	
	// using an expression
	jqMock.expectThatExceptionThrown(function() {
		throw new Error("booya");
	}, is.instanceOf(Error));
	
	/* there is a special expression for exceptions */
	
	// any exception is thrown
	jqMock.expectThatExceptionThrown(function() {
		throw new Error("anything");
	}, is.exception());	
	
	// using a string argument will assert ex.message
	jqMock.expectThatExceptionThrown(function() {
		throw new Error("bad exception 2");
	}, is.exception("bad exception 2"));	
	
	// you can pass in an object with the attributes name, message and type, 
	// which asserts ex.name, ex.message, and (ex instanceof type) respectively.
	// you can pass in just one or all three attributes.
	jqMock.expectThatExceptionThrown(function() {
		eval("blah");
	}, is.exception({name: "ReferenceError", message: "blah is not defined", type: ReferenceError}));	
</pre>





<h3>Basic Mocking</h3>
<p>Let's start with a basic hello world example of how this mock library is useful. Say you wrote this function:</p>
<pre name="code" class="js:nocontrols:nogutter">
function hello() {
    alert("hello world!");
}
</pre>

<p>You can mock and intercept the call to window.alert, and setup an expectation it is called correctly:</p>
<pre name="code" class="js:nocontrols">
jqUnit.test("hello world test", function() {
    var alertMock = new jqMock.Mock(window, "alert");
    alertMock.modify().args("hello world!").returnValue();
    hello();
    alertMock.verify();
    alertMock.restore();
});    
</pre>
<p>Lets analyse the above code, step by step.</p>
<ul>
<li>Line 2, we setup window.alert to be mocked.</li>
<li>Line 3 sets up the expectation, and says that we want to modify window.alert, setting an expection that it is called with the argument "hello world!" exactly once. It will intercept the call, and return nothing.</li>
<li>Line 4, we call the code we want to test.</li>
<li>Line 5 will verify that the expectations were satisfied. </li>
<li>Line 6 restores window.alert to its original functionality.</li>
</ul>



<h3>Modifying the Arguments of the expectation</h3>
<p>The <strong>args()</strong> method will setup the arguments of the expectation. These are basically the arguments you expect your method to be called with. Arguments will match the expectation if they are deeply equal. You can use the expressions seen earlier. You can provide any number of arguments. Here are some examples:</p>
<pre name="code" class="js:nocontrols:nogutter">
var mock = new jqMock.Mock(myobj, "fn");

mock.modify().args();
mock.modify().args([4,5,6]);
mock.modify().args( {a:'a',b:'b'}, 'c' );
mock.modify().args(is.regex(/^abc[0-9]*xyz$/));
mock.modify().args(is.anyOf(["a", "b", "c"]));
	
myobj.fn();
myobj.fn( [4,5,6] );
myobj.fn( {a:'a',b:'b'}, 'c' );
myobj.fn( "abc123xyz" )
myobj.fn("a");

mock.verify();
</pre>





<h3>Modifying the Expectation Multiplicity</h3>
<p>The multiplicity indicates how many times you expect a function to be called with some argument. When no multiplicitiy is specified as in the above examples, it defaults to a multiplicity of exactly one. These are the different ways in which multiplicity can be specified:</p>

<table>
<tr><th>Multiplicity</th><th>Meaning</th><th style="width:50%">Example</th></tr>
<tr>
    <td>mulitplicity(n)</td><td>An alias for exactly(n)</td>
    <td>
        <pre name="code" class="js:nocontrols:nogutter">
            mock.modify().args().multiplicity(2);
        </pre>
    </td>
</tr>
<tr>
    <td>exactly(n)</td><td>Expect that an argument is matched exactly n times</td>
    <td>
        <pre name="code" class="js:nocontrols:nogutter">
            mock.modify().args().multiplicity(expect.exactly(1));
        </pre>
    </td>
</tr>
<tr>
    <td>times(n)</td><td>An alias for exactly(n)</td>
    <td>
        <pre name="code" class="js:nocontrols:nogutter">
            mock.modify().args().multiplicity(expect.times(3));
        </pre>
    </td>
</tr>
<tr>
    <td>times(n,m)</td><td>range multiplicity. Expect that an argument is matched at least n times, and at most m times. In the example here, the expectation is satisfied if the method is called with no arguments 1,2 or 3 times.</td>
    <td>
        <pre name="code" class="js:nocontrols:nogutter">
            mock.modify().args().multiplicity(expect.times(1,3));
        </pre>
    </td>
</tr>
<tr>
    <td>atLeast(n)</td><td>Expect that an argument is matched at least n times.</td>
    <td>
        <pre name="code" class="js:nocontrols:nogutter">
            mock.modify().args().multiplicity(expect.atLeast(1));
        </pre>
    </td>
</tr>
<tr>
    <td>atMost(n)</td><td>Expect that an argument is matched at most n times. This argument is initially satisfied, and becomes unsatisfied if it matches more than n times.</td>
    <td>
        <pre name="code" class="js:nocontrols:nogutter">
            mock.modify().args().multiplicity(expect.atMost(4));	
        </pre>
    </td>
</tr>
</table>


<h3>Reading the Failure Report</h3>
<p>The failure report of jqMock uses the same format as the java mock library RMock, and provides a clear description of the failure. Consider the following test. We expect "Bart" to be called twice, "Lisa" once, and "Marge" at least once.</p>
<pre name="code" class="js:nocontrols">
jqUnit.test("failing test", function() {    
    var mock = new jqMock.Mock(myObj, "sayHello");
    mock.modify().args("Bart").multiplicity(2);    
    mock.modify().args("Lisa");
    mock.modify().args("Marge").multiplicity(expect.atLeast(1));    
    doWork();    
    mock.verify();
});
</pre>
<p>In the test above, line 6 calls this code under test:</p>
<pre name="code" class="js:nocontrols">
function MyObject() {};
MyObject.prototype.sayHello = function(person) {
    return "hello " + person;
};
var myObj = new MyObject();
function doWork() {
    myObj.sayHello("Bart");
	myObj.sayHello("Marge");
}
</pre>
<p>"Bart" has only been called once, and "Lisa" hasn't been called. The results will look like this:</p>

<div class="img-shadow"><img src="images/example1.png" /></div>
<br style="clear:both;" />
<br/>
<p> The following diagram shows how to read the report.</p>

<div class="img-shadow"><img src="images/example2.png" /></div>
<br style="clear:both;" />


<h3>Return Value</h3>
<p>When returnValue() is not specified, the function remains intact and you are merely checking expectations. However, you will usually want to intercept and change the return value for easy testing. Calling restore will remove all expectations, and stop intercepting the function.</p>

<pre name="code" class="js:nocontrols:nogutter">
jqUnit.test("returnValue and intercepting", function() {
    var mock = new jqMock.Mock(myObj, "sayHello");
    mock.modify().args("Bart");                       // use original call
    mock.modify().args("Homer").returnValue("doh!");  // intercept returnValue

    myObj.sayHello("Bart");   // returns "hello Bart"   
	myObj.sayHello("Homer");  // returns "doh!"
    mock.verify();
    
    mock.restore();    
    myObj.sayHello("Homer");  // after restore, returns "hello Homer"
});
</pre>


<h3>Throwing Exception</h3>
<p>You can intercept a function and specify something to be thrown as an exception when that function is called.</p>
<pre name="code" class="js:nocontrols:nogutter">
jqUnit.test("throw exception", function() {
    var mock = new jqMock.Mock(myObj, "sayHello");	
	var myError = new Error("stupid Flanders");
	mock.modify().args("Flanders").throwException(myError);	
});
</pre>




<h2>Advanced Concepts</h2>

<h3>Verifying Unexpected Invocations</h3>
<p>Most mock libraries offer the ability to check for unexpected invocations, which fails a test in the event that a method is called with arguments that have not been setup as expectations. However, this is usually too strict, <a href="http://monkeyisland.pl/2008/07/12/should-i-worry-about-the-unexpected/">and results in overspecified tests which are hard to maintain</a>.</p>
<p>By default, <b>jqMock.verify()</b> will only check any expectations you have setup. In the following example, the call on "Bart" will be ignored, while the extra call on "Homer" will show up as an error.</p>
<pre name="code" class="js:nocontrols:nogutter">
jqUnit.test("verify()", function() {  
    var mock = new jqMock.Mock(myObj, "sayHello");  
    mock.modify().args("Homer").multiplicity(1);
 
    myObj.sayHello("Bart");  // this is ignored
    myObj.sayHello("Homer"); // this will match the expectation
	myObj.sayHello("Homer"); // this will fail
	
    mock.verify();
}); 
</pre>
<p>The failure report would look like this:</p>
<div class="img-shadow"><img src="images/example8.png" /></div>
<br style="clear:both;" />


<p>However, if you want to also check for unexpected invocations, use the method <b>jqMock.verifyAll()</b>.</p>
<p>If the example code above was changed so that the last line was <b>verifyAll()</b>, then the call with "Bart" will also fail.</p>
<pre name="code" class="js:nocontrols:nogutter">
jqUnit.test("verifyAll()", function() {  
    var mock = new jqMock.Mock(myObj, "sayHello");  
    mock.modify().args("Homer").multiplicity(1);
 
    myObj.sayHello("Bart");  // this call will also fail with verifyAll
    myObj.sayHello("Homer");
	myObj.sayHello("Homer");
	
    mock.verifyAll();  // change to verifyAll
}); 
</pre>

<p>The resulting failure report would look like this:</p>
<div class="img-shadow"><img src="images/example9.png" /></div>
<br style="clear:both;" />



<h3>Ordered and Unordered Expectations</h3>
<p>So far, we have only used undordered expectations. This means expectations can be fullfilled in any order. To use strict ordering, call <strong>setOrdered(true)</strong> on the mock before setting up any expectations</p>
<pre name="code" class="js:nocontrols:nogutter">
jqUnit.test("ordered expectations", function() {
	var myobj = {echo:function(s){return s;}};
	var mock = new jqMock.Mock(myobj, "echo");
	mock.setOrdered(true); // use ordered expectations
	
	mock.modify().args(1);
	mock.modify().args(2);
	mock.modify().args(3);

	myobj.echo(1);
	myobj.echo(3);
	myobj.echo(2);
	mock.verifyAll();		
});
</pre>
<p>The results will look like the following. The call to echo(1) was satisfied. However, echo(2) was not the next call, so it stops matching the expectations.</p>

<div class="img-shadow"><img src="images/example3.png" /></div>
<br style="clear:both;" />

<h3>When you don't want to use the shortcuts</h3>
<p>It was suggested that you call <strong>addShortcut()</strong> so that the expression operator <strong>is</strong> and the multiplicity operator <strong>expect</strong> are copied to the global scope. If these conflict with your code, you can just use the original namespaced objects instead:</p>
<pre name="code" class="js:nocontrols:nogutter">
jqUnit.test("using full namespaced objects", function() {    
    var mock = new jqMock.Mock(myObj, "sayHello");
    mock.modify().args(jqMock.is.anyOf(["Lisa","Bart","Maggie"]));
    mock.modify().args("Homer").multiplicity(jqMock.expect.atLeast(1));    
    doWork();    
    mock.verify();
});
</pre>




<h3>Expectation Resolution</h3>
<p>The following section will discuss some scenarios to explain how more complex expectations are resolved.</p>
<p>In unordered expectations, matching occurs from top down, starting from the first exepctation you setup to the last. For certain types of multiplicity, they will stop matching when it hits upper limit. The following multiplicity will stop matching when the upper limit is reached, so that other expectations can pick it up:</p>
<ul>
<li>expect.exactly(n)</li>
<li>expect.times(n,m)</li>
<li>expect.atMost(n)</li>
</ul>
<p>Consider the following test, and the result.</p>
<pre name="code" class="js:nocontrols:nogutter">
jqUnit.test("upper limit", function() {    
    var mock = new jqMock.Mock(myObj, "sayHello");
    mock.modify().args("Homer").multiplicity(1);  // match once
	mock.modify().args("Homer").multiplicity(2);  // match twice
    // function is executed 4 times
    myObj.sayHello("Homer");    
    myObj.sayHello("Homer");
    myObj.sayHello("Homer");
    myObj.sayHello("Homer");
    mock.verify();
});
</pre>

<div class="img-shadow"><img src="images/example7.png" /></div>
<br style="clear:both;" />

<p>You can see that the first expectation was matched once, the next expectation was matched twice, and the test failed because there was a call which was unexpected.</p>
<p>The <strong>atLeast(n)</strong> multiplicity behaves differently, and will ALWAYS match in order to keep the expectation satisfied. Consider this test, and the result.</p>
<pre name="code" class="js:nocontrols">
jqUnit.test("atLeast", function() {    
    var mock = new jqMock.Mock(myObj, "sayHello");
    mock.modify().args("Homer").multiplicity(expect.atLeast(2));    
    mock.modify().args("Homer").multiplicity(2);    
    // function is executed 4 times
    myObj.sayHello("Homer");    
    myObj.sayHello("Homer");
    myObj.sayHello("Homer");
    myObj.sayHello("Homer");
    mock.verify();
});
</pre>

<div class="img-shadow"><img src="images/example5.png" /></div>
<br style="clear:both;" />

<p>You can see first expectation matched 4 times, while the second expectation did not match at all. If this situation happens to you, the solution is to switch lines 3 and 4, so that the <strong>atLeast()</strong> expectation doesn't steal all the matches. After the first expectation matches twice, it is disabled so that the second expectation is free to be used.</p>
<pre name="code" class="js:nocontrols:nogutter">
    mock.modify().args("Homer").multiplicity(2);
    mock.modify().args("Homer").multiplicity(expect.atLeast(2));        
</pre>

<br /><br /><br />





<script type="text/javascript" src="highlighter/shCore.js"></script>
<script type="text/javascript" src="highlighter/shBrushJScript.js"></script>
<script type="text/javascript" src="highlighter/shBrushXml.js"></script>
<script type="text/javascript">
dp.SyntaxHighlighter.ClipboardSwf = 'highlighter/clipboard.swf';
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>
